package cn.tianyue0571.brunning;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.PolylineOptions;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.tianyue0571.brunning.base.AbsBaseActivity;
import cn.tianyue0571.brunning.bean.PathRecord;
import cn.tianyue0571.brunning.inject.FindView;
import cn.tianyue0571.brunning.util.RunningDataUtil;

public class ShowMapTrackActivity extends AbsBaseActivity implements LocationSource, AMapLocationListener {
    @FindView(R.id.map)
    MapView mMapView;
    @FindView(R.id.tv_time)
    TextView mTvTime;
    @FindView(R.id.tv_souce)
    TextView mTvSource;
    @FindView(R.id.tv_sd)
    TextView mTvSpeed;
    private AMap mAMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private PolylineOptions mPolyoptions;
    private PathRecord record;
    private long starttime;
    private long endtime;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_show_map_track;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();
        initpolyline();
        if (record != null) {
            record = null;
        }
        record = new PathRecord();
        starttime = System.currentTimeMillis();
        record.setDate(getcueDate(starttime));
        myTimer.start();
    }

    @SuppressLint("SimpleDateFormat")
    private String getcueDate(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd  HH:mm:ss ");
        Date curDate = new Date(time);
        String date = formatter.format(curDate);
        return date;
    }

    private int second;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    second++;
                    mTvTime.setText(RunningDataUtil.getTime(second));
                    break;
            }
        }
    };
    private boolean isStop = false, isPause = false;
    Thread myTimer = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!isStop) {
                if (!isPause) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        Log.e("TAG", "计时器线程出现错误");
                    }
                    handler.sendEmptyMessage(1);
                }
            }
        }
    });

    private void initpolyline() {
        mPolyoptions = new PolylineOptions();
        mPolyoptions.width(10f);
        mPolyoptions.color(getResources().getColor(R.color.yellow));
    }

    private void initMap() {
        if (mAMap == null) {
            mAMap = mMapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        mAMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        mAMap.animateCamera(CameraUpdateFactory.zoomTo(16f));
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    private double distance = 0.0;
    private int index = 0;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                LatLng mylocation = new LatLng(aMapLocation.getLatitude(),
                        aMapLocation.getLongitude());
                mAMap.moveCamera(CameraUpdateFactory.changeLatLng(mylocation));
                //更新distance并且显示到textview
                int size = record.getPathline().size();
                if (size > 1) {
                    LatLng firstpoint = record.getPathline().get(size - 2);
                    LatLng secoundpoint = record.getPathline().get(size - 1);
                    if (!isPause && !isStop) {
                        distance = distance
                                + AMapUtils.calculateLineDistance(firstpoint,
                                secoundpoint);
                    }
                    //显示
                    DecimalFormat df = new DecimalFormat("0.000");
                    mTvSource.setText(df.format(distance / 1000));
                    if (distance < Double.MIN_VALUE || second / distance > 1200) {
                        mTvSpeed.setText("00'00''");
                    } else {
                        mTvSpeed.setText(RunningDataUtil.getSd(second, distance));
                    }
                }

//                if (btn.isChecked()) {
                record.addpoint(mylocation);
                mPolyoptions.add(mylocation);

                //
                redrawline();
                index++;
//                }
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": "
                        + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void redrawline() {
        if (mPolyoptions.getPoints().size() > 0) {
            mAMap.clear(true);
            mAMap.addPolyline(mPolyoptions);
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        Log.e("TAG", "active start location");
        startlocation();
    }

    private void startlocation() {
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mlocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

            mLocationOption.setInterval(200);
//            mLocationOption.setGpsFirst(true);
            mLocationOption.setWifiActiveScan(true);


            // 设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();

        }
        mlocationClient = null;
    }
}
